import hashlib
import uuid
import random
import string
from typing import Optional, Union, Any, Dict, List
import json
import base64


def generate_uuid() -> str:
    """生成UUID"""
    return str(uuid.uuid4())


def generate_short_id(length: int = 8) -> str:
    """生成短ID"""
    chars = string.ascii_uppercase + string.digits
    return ''.join(random.choice(chars) for _ in range(length))


def generate_order_number() -> str:
    """生成工单号"""
    from datetime import datetime
    
    date_str = datetime.now().strftime("%Y%m%d")
    random_num = ''.join(random.choice(string.digits) for _ in range(6))
    return f"WO{date_str}{random_num}"


def generate_work_order_number() -> str:
    """生成工单编号"""
    from datetime import datetime
    
    date_str = datetime.now().strftime("%Y%m%d")
    random_num = ''.join(random.choice(string.digits) for _ in range(6))
    return f"WO{date_str}{random_num}"


def generate_device_code(prefix: str = "DEV") -> str:
    """生成设备编码"""
    timestamp = str(int(time.time()))[-6:]  # 取时间戳后6位
    random_str = ''.join(random.choice(string.digits) for _ in range(4))
    return f"{prefix}{timestamp}{random_str}"


def md5_hash(text: str) -> str:
    """MD5哈希"""
    return hashlib.md5(text.encode()).hexdigest()


def sha256_hash(text: str) -> str:
    """SHA256哈希"""
    return hashlib.sha256(text.encode()).hexdigest()


def safe_str(obj: Any, default: str = "") -> str:
    """安全转换为字符串"""
    try:
        return str(obj) if obj is not None else default
    except:
        return default


def safe_int(obj: Any, default: int = 0) -> int:
    """安全转换为整数"""
    try:
        return int(obj)
    except:
        return default


def safe_float(obj: Any, default: float = 0.0) -> float:
    """安全转换为浮点数"""
    try:
        return float(obj)
    except:
        return default


def safe_bool(obj: Any, default: bool = False) -> bool:
    """安全转换为布尔值"""
    try:
        if isinstance(obj, bool):
            return obj
        if isinstance(obj, str):
            return obj.lower() in ['true', '1', 'yes', 'on', 'y']
        return bool(obj)
    except:
        return default


def safe_json_loads(json_str: str, default: Any = None) -> Any:
    """安全JSON解析"""
    try:
        return json.loads(json_str)
    except:
        return default


def safe_json_dumps(obj: Any, default: str = "{}") -> str:
    """安全JSON序列化"""
    try:
        return json.dumps(obj, ensure_ascii=False, default=str)
    except:
        return default


def mask_sensitive_data(data: str, mask_char: str = "*", keep_start: int = 2, keep_end: int = 2) -> str:
    """脱敏敏感数据"""
    if len(data) <= keep_start + keep_end:
        return mask_char * len(data)
    
    start = data[:keep_start]
    end = data[-keep_end:] if keep_end > 0 else ""
    middle = mask_char * (len(data) - keep_start - keep_end)
    
    return f"{start}{middle}{end}"


def mask_phone(phone: str) -> str:
    """脱敏手机号"""
    if len(phone) != 11:
        return mask_sensitive_data(phone)
    
    return f"{phone[:3]}****{phone[-4:]}"


def mask_email(email: str) -> str:
    """脱敏邮箱"""
    if '@' not in email:
        return mask_sensitive_data(email)
    
    username, domain = email.split('@', 1)
    if len(username) <= 2:
        masked_username = '*' * len(username)
    else:
        masked_username = username[0] + '*' * (len(username) - 2) + username[-1]
    
    return f"{masked_username}@{domain}"


def mask_id_card(id_card: str) -> str:
    """脱敏身份证号"""
    if len(id_card) == 18:
        return f"{id_card[:6]}********{id_card[-4:]}"
    elif len(id_card) == 15:
        return f"{id_card[:6]}*****{id_card[-4:]}"
    else:
        return mask_sensitive_data(id_card)


def deep_merge_dict(base: Dict, update: Dict) -> Dict:
    """深度合并字典"""
    result = base.copy()
    
    for key, value in update.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key] = deep_merge_dict(result[key], value)
        else:
            result[key] = value
    
    return result


def flatten_dict(data: Dict, parent_key: str = '', sep: str = '.') -> Dict:
    """扁平化字典"""
    items = []
    
    for key, value in data.items():
        new_key = f"{parent_key}{sep}{key}" if parent_key else key
        
        if isinstance(value, dict):
            items.extend(flatten_dict(value, new_key, sep).items())
        else:
            items.append((new_key, value))
    
    return dict(items)


def chunk_list(data: List, chunk_size: int) -> List[List]:
    """分块列表"""
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def remove_duplicates(data: List, key_func: callable = None) -> List:
    """去重列表"""
    if key_func is None:
        return list(dict.fromkeys(data))
    
    seen = set()
    result = []
    
    for item in data:
        key = key_func(item)
        if key not in seen:
            seen.add(key)
            result.append(item)
    
    return result


def group_by(data: List, key_func: callable) -> Dict:
    """按条件分组"""
    groups = {}
    
    for item in data:
        key = key_func(item)
        if key not in groups:
            groups[key] = []
        groups[key].append(item)
    
    return groups


def sort_by(data: List, key_func: callable, reverse: bool = False) -> List:
    """按条件排序"""
    return sorted(data, key=key_func, reverse=reverse)


def filter_by(data: List, filter_func: callable) -> List:
    """按条件过滤"""
    return [item for item in data if filter_func(item)]


def base64_encode(data: Union[str, bytes]) -> str:
    """Base64编码"""
    if isinstance(data, str):
        data = data.encode('utf-8')
    return base64.b64encode(data).decode('ascii')


def base64_decode(encoded_data: str) -> str:
    """Base64解码"""
    try:
        decoded_bytes = base64.b64decode(encoded_data)
        return decoded_bytes.decode('utf-8')
    except:
        return ""


def format_file_size(size_bytes: int) -> str:
    """格式化文件大小"""
    if size_bytes == 0:
        return "0B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    
    while size_bytes >= 1024 and i < len(size_names) - 1:
        size_bytes /= 1024.0
        i += 1
    
    return f"{size_bytes:.1f}{size_names[i]}"


def format_number(number: Union[int, float], decimals: int = 2) -> str:
    """格式化数字，添加千位分隔符"""
    if isinstance(number, int):
        return f"{number:,}"
    else:
        return f"{number:,.{decimals}f}"


def truncate_string(text: str, max_length: int, suffix: str = "...") -> str:
    """截断字符串"""
    if len(text) <= max_length:
        return text
    
    return text[:max_length - len(suffix)] + suffix


def camel_to_snake(name: str) -> str:
    """驼峰转蛇形"""
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
    return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()


def snake_to_camel(name: str, capitalize_first: bool = False) -> str:
    """蛇形转驼峰"""
    components = name.split('_')
    
    if capitalize_first:
        return ''.join(word.capitalize() for word in components)
    else:
        return components[0] + ''.join(word.capitalize() for word in components[1:])


def is_empty(value: Any) -> bool:
    """判断值是否为空"""
    if value is None:
        return True
    
    if isinstance(value, (str, list, dict, tuple, set)):
        return len(value) == 0
    
    return False


def coalesce(*args) -> Any:
    """返回第一个非空值"""
    for arg in args:
        if not is_empty(arg):
            return arg
    return None


import time
import re


class Timer:
    """计时器类"""
    
    def __init__(self):
        self.start_time = None
        self.end_time = None
    
    def start(self):
        """开始计时"""
        self.start_time = time.time()
        self.end_time = None
    
    def stop(self):
        """停止计时"""
        if self.start_time is None:
            raise ValueError("计时器尚未启动")
        
        self.end_time = time.time()
    
    def elapsed(self) -> float:
        """获取已用时间（秒）"""
        if self.start_time is None:
            return 0
        
        end_time = self.end_time or time.time()
        return end_time - self.start_time
    
    def __enter__(self):
        self.start()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()